package com.qingyun.common.utils.mp3;

import com.qingyun.common.config.QingYunConfig;
import com.qingyun.common.constant.Constants;
import lombok.Data;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.id3.ID3v23Frame;

import java.io.File;
import java.sql.Time;

@Data
public class Mp3Utils {


	private Mp3Utils(){}

	/**
	 * @param mp3Url mp3网络url地址
	 */
	public static Mp3Info instance(String mp3Url) throws Exception {
		// 网络url转为文件
//		HttpURLConnection httpUrl = (HttpURLConnection) new URL(mp3Url).openConnection();
//		httpUrl.connect();
//		File file = FileUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID() + ".mp3");
		String profile = QingYunConfig.getProfile();
		String[] split = mp3Url.split(Constants.RESOURCE_PREFIX);
		File file = new File(profile + split[1]);

		// 读取文件信息
		MP3File mp3File  = (MP3File) AudioFileIO.read(file);
		// 获取头
		MP3AudioHeader audioHeader = (MP3AudioHeader) mp3File.getAudioHeader();

//		//歌名
//		ID3v23Frame songnameFrame = (ID3v23Frame) mp3File.getID3v2Tag().frameMap.get("TIT2");
//		String songName = songnameFrame.getContent();
//		//歌手
//		ID3v23Frame artistFrame = (ID3v23Frame) mp3File.getID3v2Tag().frameMap.get("TPE1");
//		String artist = artistFrame.getContent();
//		//专辑
//		ID3v23Frame albumFrame = (ID3v23Frame) mp3File.getID3v2Tag().frameMap.get("TALB");
//		String album = albumFrame.getContent();
		//时长
		int duration = audioHeader.getTrackLength();

		return new Mp3Info(null,null,null, duration);
	}

	/**
	 * 秒转换为指定时间格式
	 *
	 */
	public static String secondToDate(int second) {
		//转换为毫秒,但需要减去最基础的8小时
		Time time = new Time(second * 1000L - 8 * 60 * 60 * 1000);
		return time.toString();
	}
}

